<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/axios-interceptors.js"></script>
    <script src="../js/vue3.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <link href="../css/index.css" rel="stylesheet"/>
    <style>
        body {
            background-color: #f5f7fa;
            padding: 20px;
            font-family: "Microsoft YaHei", sans-serif;
        }
        .user-container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
            padding: 20px;
        }
        .el-table .el-button {
            margin-right: 5px;
            border-radius: 4px;
            transition: all 0.2s;
        }
        .edit-btn:hover {
            color: #66b1ff;
        }
        .delete-btn:hover {
            color: #f78989;
        }
        .assign-role-btn:hover {
            color: #409eff;
        }
        .pagination-block {
            margin-top: 16px;
        }
        .user-table {
            border-radius: 8px;
            overflow: hidden;
        }
        .el-table th {
            background-color: #f0f7ff;
            color: #333;
            font-weight: 500;
            border-bottom: 1px solid #e6f7ff;
        }
        .el-table td {
            border-bottom: 1px solid #f5f7fa;
        }
        .el-dialog {
            border-radius: 8px;
        }
        .el-form-item {
            margin-bottom: 16px;
        }
        .el-input {
            border-radius: 4px;
        }
        .el-button {
            transition: all 0.3s;
        }
        .el-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        .role-table {
            margin-bottom: 16px;
        }
    </style>
</head>
<body>
<div id="app" class="user-container">
<!--  界面表格  -->
    <div>
        <el-table
                :data="users"
                class="user-table"
                border
                stripe
        >
            <el-table-column label="编号" prop="id" width="80" align="center"></el-table-column>
            <el-table-column label="用户名" prop="username" min-width="150" align="center"></el-table-column>
            <el-table-column align="center" label="操作" width="240">
                <template #default="scope">
                    <el-button size="small" class="edit-btn" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button
                            size="small"
                            type="danger"
                            class="delete-btn"
                            @click="handleDelete(scope.row)"
                    >
                        删除
                    </el-button>
                    <el-button
                            size="small"
                            type="primary"
                            class="assign-role-btn"
                            @click="showAssignRoleDialog(scope.row)"
                    >
                        分配角色
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--  分页  -->
        <div class="pagination-block">
            <el-pagination
                    v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 15]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            ></el-pagination>
        </div>
    </div>

    <!-- 编辑用户弹窗 -->
    <div>
        <el-dialog title="编辑用户"
                   v-model="EditDialogVisible"
                   :before-close="closeDialog"
                   width="500px">
            <el-form :model="userForm" ref="userFormRef" :rules="editRules" label-width="100px">
                <el-form-item label="用户ID" prop="id">
                <el-input
                        v-model="userForm.id"
                        readonly
                        :disabled="true"></el-input>
                </el-form-item>

                <!-- 用户名（必填） -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>

                <!-- 头像 -->
                <el-form-item label="头像" width="120">
                    <el-upload
                    action="/api/upload/avatar"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :show-file-list="false"
                    >
                    <img
                            v-if="userForm.pic"
                            :src="userForm.pic"
                            style="width: 70px; height: 70px; object-fit: cover; border-radius: 4px; cursor: pointer;"
                    >
                    <div v-else style="width: 70px; height: 70px; background: #f5f7fa; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #909399; cursor: pointer;">
                        点击上传
                    </div>
                    </el-upload>
                </el-form-item>

                <el-form-item label="角色类型" prop="type">
                    <el-select v-model="userForm.type" placeholder="请选择角色类型">
                        <el-option label="房东" :value="0"></el-option>
                        <el-option label="管理员" :value="1"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 状态（必填，下拉框） -->
                <el-form-item label="用户状态" prop="status">
                    <el-select v-model="userForm.status" placeholder="请选择用户状态">
                        <el-option label="禁用" :value="0"></el-option>
                        <el-option label="可用" :value="1"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 注册时间 -->
                <el-form-item label="注册时间">
                    <el-date-picker v-model="userForm.createTime" type="datetime"
                                    disabled placeholder="注册时间" readonly></el-date-picker>
                </el-form-item>

                <!-- 备注 -->
                <el-form-item label="备注">
                    <el-input v-model="userForm.remarks" type="textarea" placeholder="备注信息"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>
    </div>


    <!--  分配角色弹窗  -->
    <div>
        <el-dialog v-model="AssignDialogVisible" title="分配角色" width="600px">
            <el-table
                    ref="multipleTableRef"
                    :data="roles"
                    border
                    class="role-table"
                    @selection-change="handleRoleSelectionChange"
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="ID" prop="id" width="80" align="center"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" min-width="150"></el-table-column>
                <el-table-column label="角色编码" prop="roleCode" min-width="150"></el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="AssignDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveRoles">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>


</div>

<script>
    const { createApp, reactive, ref, onMounted,nextTick} = Vue;
    const { ElMessage,ElMessageBox} = ElementPlus;

    const app = createApp({
        setup() {

            //分页
            const pageNum = ref(1);
            const pageSize = ref(5);
            const total = ref(0);

            //表格数据源
            const users = ref([]);

            // 分配弹窗显示控制
            const AssignDialogVisible = ref(false);
            //编辑弹窗显示控制
            const EditDialogVisible = ref(false);
            //编辑弹窗状态显示数组
            const statusList=ref([])
//编辑功能===================================================================================================
            //编辑弹窗数据源
            const userForm =ref([]);
            //分配角色弹窗数据源
            const roles = ref([]);

            //编辑角色摁钮功能
            const handleEdit = (row) => {
                userForm.value = {
                    id: row.id,
                    username: row.username,
                    pic:row.pic,
                    type: row.type,
                    status: row.status,
                    createTime: row.createTime,
                    remarks: row.remarks
                };
                EditDialogVisible.value= true;
            };

            //头像编辑功能相关
            const handleAvatarSuccess = (response, file) => {
                // 假设接口返回新的头像地址
                userForm.value.pic = response.data.avatarUrl;
                ElMessage.success('头像上传成功');
            };
            //头像图片格式验证
            const beforeAvatarUpload = (file) => {
                // 限制文件类型（仅允许图片）
                const isImage = file.type.startsWith('image/');
                if (!isImage) {
                    ElMessage.error('只能上传图片文件');
                    return false;
                }
                // 限制文件大小（示例：不超过 2MB）
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    ElMessage.error('图片大小不能超过 2MB');
                    return false;
                }
                return true;
            };

            //编辑弹窗确定摁钮
            const handleSave =()=>{
                axios.post(`/user/updateUser`,userForm.value).then((resp)=>{
                  if (resp.data.code === 200){
                      ElMessage.success(resp.data.msg);
                      loadUsers();
                      EditDialogVisible.value = false;
                  }
                }).catch(error=>{
                    ElMessage.error(error.response.data.msg);
                })
            }

            //编辑框取消摁钮
            const closeDialog=()=>{
                clearValid();
                EditDialogVisible.value = false;
            }

            //删除摁钮功能
            const handleDelete = (row) => {
                ElMessageBox.confirm('将永久删除该电影信息. 确定?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        axios.delete(`/user/deleteUser/${row.id}`).then(resp=>{
                             if (resp.data.code === 200){
                                 ElMessage.success(resp.data.msg);
                                 loadUsers();
                             }
                        }).catch(error=>{
                            ElMessage.error(error.response.data.msg);
                        })
                    })
            };

            //获取分配弹窗实例
            const multipleTableRef=ref(null)
            // 存储当前要分配角色的用户ID
            const currentUserId = ref(null);
            //分配角色摁钮
            const showAssignRoleDialog = (row) => {
                //获取用户id
                currentUserId.value=row.id

                axios.get(`/role/${row.id}`).then((resp) => {
                    roles.value = resp.data.obj;
                    nextTick(()=>{
                        roles.value.forEach(role=>{
                            //如果flg为true
                            if(role.flg){
                                multipleTableRef.value.toggleRowSelection(role,true)
                            }
                        })
                    })
                }).catch(error=>{
                    ElMessage.error(error.response.data.msg)
                })
                AssignDialogVisible.value = true;
            };
//角色多选框业务==================================================================================================================
            //多选框桥梁绑定数据
            const ids=ref([])
            //分配角色功能多选框
            const handleRoleSelectionChange = (val) => {
                ids.value = val.map(item=>item.id);
            };

            //分配弹窗保存摁钮
            const saveRoles = () => {
               axios.post(`/role/saveRole/${currentUserId.value}`,ids.value).then(resp=>{
                     if (resp.data.code === 200){
                         ElMessage.success(resp.data.msg)
                     }
               }).catch(error=>{
                   ElMessage.error(error.response.data.msg)
               })
                AssignDialogVisible.value = false;
            };



            //刷新表格数据
            const loadUsers =()=>{
                axios.get(`/user/${pageNum.value}/${pageSize.value}`)
                    .then(resp => {
                        users.value = resp.data.obj.data
                        total.value = resp.data.obj.total
                    })
                    .catch((error) => {
                        ElMessage.error(error.response.data.msg)
                    })
            }

            //弹窗表单引用
            const userFormRef= ref(null);
            // 清空校验红字信息
            const clearValid = () => {
                if (userFormRef && userFormRef.value) {
                    userFormRef.value.resetFields();
                }
            }


            //分页
            const handleSizeChange = (val) => {
                pageSize.value = val;

            };
            const handleCurrentChange = (val) => {
                pageNum.value = val;
            };

            // 编辑表单验证规则
            const editRules = reactive({
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '用户名长度在3-20个字符之间', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
                ],
                phone: [
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                status: [
                    { required: true, message: '请选择用户状态', trigger: 'change' }
                ]
            });

            onMounted(() => {
                loadUsers();
            });

            return {
                users,
                pageNum,
                pageSize,
                total,
                AssignDialogVisible,
                roles,
                EditDialogVisible,
                editRules,
                userForm,
                statusList,
                multipleTableRef,
                currentUserId,
                userFormRef,
                handleEdit,
                handleDelete,
                showAssignRoleDialog,
                handleRoleSelectionChange,
                saveRoles,
                handleSizeChange,
                handleCurrentChange,
                loadUsers,
                handleAvatarSuccess,
                beforeAvatarUpload,
                handleSave,
                clearValid,
                closeDialog,
            };
        }
    });

    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });

    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }

    app.mount('#app');
</script>
</body>
</html>